package com.probiz.estoresa.system.web.action;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.Constants;
import com.probiz.estore.common.helper.JFieldErrorUtil;
import com.probiz.estore.common.model.system.AppResource;
import com.probiz.estore.core.controller.GenericStoreAdminController;
import com.probiz.estore.core.exception.ApplicationException;
import com.probiz.estore.core.model.JFieldError;
import com.probiz.estore.core.search.SearchCriteria;
import com.probiz.estore.core.util.ContextUtil;
import com.probiz.estore.system.service.AppResourceManager;

public class AppResourceController extends GenericStoreAdminController<AppResource> {
    private AppResourceManager appResourceManager = null;
    private Short belongTo = null;
    public void setBelongTo(Short belongTo) {
		this.belongTo = belongTo;
	}
    public void setAppResourceManager(AppResourceManager inMgr) {
        this.appResourceManager = inMgr;
    }

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericController#getEntityName(java.lang.Object)
	 */
	@Override
	protected String getEntityName(AppResource entity) {
		return entity.getResourceName();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.BaseController#initController()
	 */
	@Override
	protected void initController() throws Exception {
		mgr = appResourceManager;
	}
	
	public ModelAndView defaultAction(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mav = new ModelAndView(listView);
		String parentId = request.getParameter("parentId");
		parentId=StringUtils.isBlank(parentId)?"-1":parentId;
		mav.addObject("parentId",parentId);
		return mav;
	}
	
	public ModelAndView loadResources(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String[]beans = ContextUtil.getSpringContext().getBeanDefinitionNames();
		int sort=1;
		String rn="";
		Object obj="";
		for(String k:beans){
			try{
				if(k.endsWith("Manager")){
					obj = ContextUtil.getSpringBeanById(k);
					rn=obj.toString();
				}
			}catch(Exception e){
				continue;
			}
			if(!rn.startsWith("com.probiz.estore."))
				continue;
			System.out.println(rn);
			Matcher mt = Pattern.compile("com.probiz.estore.(.*?).service..*"+k.substring(2)+"Impl").matcher(rn);
			if(mt.find()){
				AppResource res = new AppResource();
				res.setBelongTo(belongTo);
				res.setResourceName(k);
				res.setResourceString(mt.group());
				res.setEnableDataAuthz(belongTo);
				appResourceManager.configToDb(res);
			}
		}
		return defaultAction(request,response);
	}
	
	public ModelAndView search(HttpServletRequest request,HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("system/include/resourceListBody");
		SearchCriteria sc = createSearchCriteria(request);
		List results = appResourceManager.searchByCriteria(sc,belongTo);
		mav.addObject("appResourceList", results);
		return mav;
	}
	
	public ModelAndView multiDelete(HttpServletRequest request,
			HttpServletResponse response) {
		// 取得要删除的记录的id的列表。注意：选择框的id要是"multiIds"。
		String[] ids = request.getParameterValues("multiIds");
		if (ids != null && ids.length > 0) {
			try{
				appResourceManager.deleteAllByIds(ids);
			}catch (DataIntegrityViolationException e) {
				//Hibernate底层仍会log此出错误信息
				this.saveErrorMessage(request, this.getMessage("common.message.delete.constraintViolation"));
				return defaultAction(request, response);
			}
			String message = getMessage("common.deleted.multi", new Object[] {getEntityTypeMessage(), ids.length });
			saveMessage(request, message);
		}
		return getRedirectToActionView("defaultAction");
	}
	
		
	@Override
	public ModelAndView save(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 取得Form对应的Model
		AppResource entity = formBackingObject(request);
		entity.setEnableDataAuthz(belongTo);
		entity.setBelongTo(belongTo);
		BindException errors = null;
		try {
			ServletRequestDataBinder binder = bindAndValidate(request, entity);
			errors = new BindException(binder.getBindingResult());
			// 查看是否有相同的匹配字串
			if(appResourceManager.isPatternExist(entity.getResourceString(), entity.getResourceId())){
				errors.rejectValue("resourceString", "appResource.pattern.exist");
			}
			if (!errors.hasErrors()) {// 里面如果出错应该抛出异常
				//保存，新的权限资源将被授权给超级管理员
				appResourceManager.save(entity);
				boolean isNew = isEntityNew(request);
				if(isNew){
					saveMessage(request, getMessage("appResource.default.grant", new Object[] {Constants.DEFAULT_ADMIN_ROLE_NAME}));
				}
				String msgKey = isNew ? "common.added" : "common.updated";
				saveMessage(request,  getMessage(msgKey, new Object[] {	getEntityTypeMessage(), getEntityName(entity) }));
			}
		} catch (ApplicationException e) {
			handleApplicationException(errors, e);
		}

		Map<String, Object> data = new HashMap<String, Object>();
		if (errors.hasErrors()) {
			List<JFieldError> jFiledErrors = JFieldErrorUtil.getFiledErrors(errors);
			data.put("rtn", "error");
			data.put("jFiledErrors", jFiledErrors);
		} else{
			data.put("rtn", "success");
		}
		
		JSONObject jsonMap = JSONObject.fromObject(data);
		PrintWriter out = response.getWriter();
		out.println(jsonMap.toString());
		
		return null;
	}
	@Override
	protected void onShowForm(HttpServletRequest request, ModelAndView mv){
		String parentId = request.getParameter("parentId");
		request.setAttribute("parentId", parentId);
		request.setAttribute("requestURI", request.getRequestURI());
		
	}
	@Override
	protected void preSave(HttpServletRequest request, AppResource entity, BindException errors) {
		
	}

}
